package com.example.log.alarm.advice.exeception;

import net.bytebuddy.asm.Advice;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

/**
 * @program: spring-agent
 * @description:
 * @author: zt22328 赵儒定
 * @create: 2023-05-05 09:38
 **/
public class ThrowableAdviceInterceptor {

    /**
     * 方法拦截
     * new Throwable();
     * @param object
     */
    @Advice.OnMethodExit()
    public static void exit(@Advice.This Object object) {
        String threadName = Thread.currentThread().getName();
        if (!(object instanceof Throwable)
                || "main".equals(threadName)
                || threadName.startsWith("RMI TCP Connection")
                || "Stack trace".equals(object.toString())) {
            return;
        }
        // SPY
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("threadName", threadName);
            map.put("triggerTime", LocalDateTime.now());
            map.put("throwable", object);
            Class<?> aClass = Class.forName("com.example.log.alarm.spy.BootstrapQueuedSpy_internal");
            Field throwableQueue = aClass.getDeclaredField("throwableQueue");
            throwableQueue.setAccessible(true);
            BlockingQueue<Map<String, Object>> queue = (BlockingQueue<Map<String, Object>>) throwableQueue.get(null);
            queue.offer(map);
        } catch (Exception e) {
            System.out.println("Throwable：" + e.getMessage());
        }
    }

}
